# coding:utf-8
from BigDataWeb.algorithm import Algorithm

'''
关联规则
'''


class Associator(Algorithm):
    # 事务项清单,例如:[('eggs','bacon','soup'),('eggs','bacon','apple')]
    transactions = []
    # 例如:"订单ID"
    transaction_id_name = ""
    # 例如:"购物项"
    transaction_goods_name = ""
    # 频繁项目集
    itemsets = {}
    # 关联规则清单
    rules = []
    # 最小支持度(0~1)
    min_support = 0.2
    # 最小置信度(0~1)
    min_confidence = 1
    
    def __init__(self):
        Algorithm.__init__(self)
        # 不创建字段描述图表
        self.will_create_field_desc_chart = False;

    def setInPutFieldName(self, transaction_id_name, transaction_goods_name):
        self.transaction_id_name = transaction_id_name
        self.transaction_goods_name = transaction_goods_name
        # 整理transactions
        self.transactions = []
        for item in self.data_source.groupby(self.transaction_id_name):
            self.transactions.append(tuple(item[1][self.transaction_goods_name].values))
    
    def prepareIpynbItems(self):
        Algorithm.prepareIpynbItems(self)
        self.ipynb_items["#transaction_id_name#"] = self.transaction_id_name
        self.ipynb_items["#transaction_goods_name#"] = self.transaction_goods_name
        self.ipynb_items["#min_support#"] = self.min_support
        self.ipynb_items["#min_confidence#"] = self.min_confidence
